package com.liu.manag.controller;

import com.liu.manag.entity.File;
import com.liu.manag.entity.User;
import com.liu.manag.enums.FileTypeEnum;
import com.liu.manag.security.UserAuthenticationExtractor;
import com.liu.manag.service.FileService;
import com.liu.manag.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.Principal;
import java.util.List;

@RestController
@RequestMapping
public class FileController {

    @Autowired
    private FileService fileService;

    @GetMapping("/folder/{folderId}")
    public Result<List<File>> getFiles(@PathVariable("folderId") Long folderId,
                                       Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);
        fileService.findByFolderId(folderId, operator);
        return null;
    }

    @PostMapping("/folder")
    public Result<String> createFolder(@RequestParam("parentId") Long parentId,
                                       @RequestParam("folderName") String folderName,
                                       Principal principal) {

        User operator = UserAuthenticationExtractor.extract(principal);
        fileService.addFolder(parentId, folderName, operator);
        return new Result<>("新建成功");
    }

    @PutMapping("/file")
    public Result<String> updateFileName(@RequestParam("fileName") String fileName,
                                         @RequestParam("fileId") Long fileId,
                                         Principal principal) {
        User operator = UserAuthenticationExtractor.extract(principal);
        File file = fileService.queryById(fileId);
        Result<String> result = new Result<>("修改成功");
        if (file == null) {
            result.setCode(400);
            result.setStatus(400);
            result.setMessage("请求成功");
            result.setData("您没有权限");
        }

        file.setFileName(fileName);
        fileService.update(file);
        return result;

    }

    @GetMapping("/{fileId}")
    public Result<List<File>> getFilesByFileId() {
        return null;
    }

    /**
     * 修改文件名
     *
     * @return
     */
    @PutMapping("")
    public Result<String> updateFile() {
        return null;
    }

    @GetMapping("/download")
    public ResponseEntity<Object> download(@RequestParam("fileId")Long fileId) throws FileNotFoundException, UnsupportedEncodingException {
        File file = fileService.queryById(fileId);
        if(file == null || file.getFileType().equalsIgnoreCase(FileTypeEnum.FOLDER.toString())){
            return null ;
        }
        java.io.File ioFile = new java.io.File(file.getRealPath());
        InputStreamResource resource = new InputStreamResource(new FileInputStream(ioFile));
        HttpHeaders headers =new HttpHeaders();
        headers.add("Content-Disposition",String.format("attachment;filename=\"%s\"", URLEncoder.encode(file.getFileName(),"utf-8")));
        headers.add("Cache-Control","no-cache,no-store,must-revalidate");
        headers.add("Pragma","mo-cache");
        headers.add("Expires","0");

        ResponseEntity<Object> responseEntity = ResponseEntity.ok()
                .headers(headers)
                .contentLength(ioFile.length())
                .contentType(MediaType.parseMediaType("application/text;charset=utf-8"))
                .body(resource);

        return responseEntity;

    }

    @DeleteMapping
    public Result<String> deleteFile(@RequestParam("fileId") Long fileId) {
        fileService.deleteById(fileId);
        return new Result<>("删除成功");
    }
}
